﻿package com.bjsxt.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated; 
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.bjsxt.commons.Constants;
import com.bjsxt.po.Admin;
import com.bjsxt.po.ChartModel;
import com.bjsxt.po.Department;
import com.bjsxt.service.AdminService;
import com.bjsxt.service.DepartmentService;
import com.bjsxt.utils.UserException;
import com.sun.javafx.sg.prism.NGShape.Mode;
/**
 * 管理员登陆和系统功能的控制器
 * 
 *
 */
 
@Controller
@SessionAttributes("username")
public class SystemController { 
	
	@Resource AdminService adminService;  
	@Autowired DepartmentService departmentService;
	
	
	/**
	 * 实现三天免登陆
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login(Model model,HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		boolean flag=false;
		if(cookies!=null&&cookies.length>0){
			for(Cookie c:cookies){
				if(c.getName().equals("login")){
					flag=true;
					break;
				}
			}
		}
		if(flag){
		  return "main";		
		}
		model.addAttribute(new Admin());
		return "login";
	}
	/*
	 * 处理用户登录
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public void login(@Validated Admin admin,BindingResult br,Model model,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception { 
		boolean success = true;
		String msg = ""; 
		
		if(br.hasErrors()) {
			msg = br.getAllErrors().toString();
			success = false;  
		} 
		if (!adminService.checkLogin(admin)) { 
			msg = adminService.getErrMessage();
			success = false; 
		} 
		if(success) {
			//实现三天免登陆
			Cookie cookie=new Cookie("login","login");
			cookie.setMaxAge(60*60*24*3);
			response.addCookie(cookie);
			session.setAttribute("username", admin.getUsername()); 
			ServletContext sc = request.getServletContext();
			HttpSession ss= (HttpSession) sc.getAttribute(admin.getUsername());
			session.setAttribute("admin", admin);
			if(ss!=null){
				ss.invalidate();
			}
			sc.setAttribute(admin.getUsername(),session);	
		}  
        response.setContentType("text/json;charset=UTF-8");  
        PrintWriter out = response.getWriter();  
        //将要被返回到客户端的对象   
        JSONObject json=new JSONObject();   
        json.accumulate("success", success);
        json.accumulate("msg", msg);
        out.println(json.toString());   
        out.flush();  
        out.close();  
	}
	
	/**
	 * 处理用户退出后的操作，将返回到登陆界面
	 * @param model
	 * @param session
	 * @return  
	 */
	@RequestMapping("/logout")
	public String logout(Model model,HttpSession session) {
		model.asMap().remove("username"); 
		session.invalidate();
		return "redirect:/login";
	}
	
	/**
	 * 修改密码操作
	 * @param oldPassword  旧密码
	 * @param newPassword  新密码
	 * @param newPassword2  再次确认密码
	 * @param request
	 * @param session 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/changePassword",method=RequestMethod.POST)
	public String ChangePassword(String oldPassword,String newPassword,String newPassword2,HttpServletRequest request,HttpSession session) throws Exception { 
		if(oldPassword.equals("")) throw new UserException("请输入旧密码！");
		if(newPassword.equals("")) throw new UserException("请输入新密码！");
		if(!newPassword.equals(newPassword2)) throw new UserException("两次新密码输入不一致"); 
		
		String username = (String)session.getAttribute("username");
		if(username == null) throw new UserException("session会话超时，请重新登录系统!");
		 
		
		Admin admin = adminService.findAdminByUserName(username); 
		if(!admin.getPassword().equals(oldPassword)) throw new UserException("输入的旧密码不正确!");
		
		try { 
			adminService.changePassword(username,newPassword);
			request.setAttribute("message", java.net.URLEncoder.encode(
					"密码修改成功!", "utf-8"));
			return "message";
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("error", java.net.URLEncoder
					.encode("密码修改失败!","utf-8"));
			return "error";
		}   
	}
	/**
	 * 返回用户的信息图标
	 * 显示部门信息的男女比例
	 */
	@RequestMapping("/charts")
	@ResponseBody
    public ChartModel getChartsData(){
		ChartModel cm=new ChartModel();
        cm.getTitle().put("text","部门员工男女比例表");
        //得到所有的部门
        List<String> xAxis=this.departmentService.queryDepartmentAllName();
        cm.getxAxis().put("categories",xAxis);
        //有几个值
         
        	Map<String,Object> map1=new HashMap<>();
        	map1.put("type","column");
        	map1.put("name","male");
        	List<Integer> list=new ArrayList<>();
        	Random random=new Random();
        	for(int i=0;i<xAxis.size();i++){
        		list.add(random.nextInt(8)+1);
        	}
        	map1.put("data",list);
        	cm.getSeries().add(map1);
        	
        	Map<String,Object> map2=new HashMap<>();
        	map2.put("type","column");
        	map2.put("name", "female");
        	List<Integer> list1=new ArrayList<>();
        	for(int i=0;i<xAxis.size();i++){
        		list1.add(random.nextInt(7)+1);
        	}
        	map2.put("data",list1);
        	cm.getSeries().add(map2);
        	
        
		return cm;
    }
}
